package com.adon.ar.test;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import ken.app.bean.GetCameraBabyBean;
import ken.app.bean.GetStoreInfoBean;
import ken.app.bean.GuestRecordUploadBean;
import ken.app.bean.IndustryBabyBean;
import ken.app.bean.MemberGoodBean;
import ken.app.bean.PersonalBean;
import ken.app.bean.TreeSingleBean;
import ken.app.even.Event;
import ken.app.even.GuestRecordUploadEvent;
import ken.app.even.IndustryBabyEvent;
import ken.app.even.KenEventManager;
import ken.app.even.MemberGoodEvent;
import ken.app.even.QueryTreeContentEvent;
import ken.app.even.iface.IEventCallback;
import ken.app.helper.Helper;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.method.Touch;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.adon.ar.test.StoreView.StoreType;
import com.she.olympic.MessageGiftActivity;
import com.she.olympic.Olympic;
import com.she.olympic.R;
import com.she.olympic.StoreInfoPageActivity;
import com.she.olympic.TreeActivity;


public class ARExampleActivity extends Activity {
	private FrameLayout mLayout;
	// private ARCameraView mARCameraView;
	private CameraPreview mCameraPreview;
	private Camera mCamera;
	private LocationManager mLocationManager;
	private SensorManager mSensorManager;
	private List<Sensor> mOrientationSensors, mAccelerometerSensors;
	private ARpoi poi;

	private List<GetCameraBabyBean> getCameraBabyData; // 可照集寶寶列表ArrayList
	private List<GetStoreInfoBean> storeInfoData;// 商家列表ArrayList
	private List<OriginalParameter> poiList = new ArrayList<OriginalParameter>();
	private List<SampleView> sampViewList = new ArrayList<SampleView>();
	private List<StoreView> storeViewList = new ArrayList<StoreView>();

	// TODO test
	StoreView storeView;
	// ======================

	private int[] xList;
	private int[] yList;

	private int width;
	private int height;
	private int padAngle = 0;
	private float focalLength;
	private static float CAMERAANGLE = 25.0f;
	private Location user_loc;
	// private boolean up = false, down = false;
	private float /* angle, */speed, rotation_angle/* , y_movement */;
	// private float angle[] = new float[BABY_COUNT]/*, speed[] = new
	// float[BABY_COUNT], rotation_angle[] = new float[BABY_COUNT], y_movement[]
	// = new float[BABY_COUNT]*/;

	private TextView latitude, longitude, high;
	private int x_Correction, y_Correction; // x, y 軸 校正值

	// zoom in / zoom out
	private static final int Z_AXIS = 1;// 寶寶圖片大小
	private static final int Distance_to_user = 200;
	private int BABY_COUNT;

	// focus and capture
	private ViewFlipper focus_frame;
	private ViewFlipper store_switch;
	private ImageView toolbtn_Capture, toolbtn_CaptureInfo, toolbtn_Cancel, img_CaptureInfo, cancle_CaptureInfo, img_UncaptureInfo;
	protected boolean uncaptureInfoVisible = false;
	private boolean isFocus[];
	private boolean storeSwitch;
	private boolean isPad = false;
	private AlertDialog.Builder dialog;
	private static final int DISTANCE = 120;
	// private ImageView mScreenShot ,mCameraView;
	// private Bitmap mScreenShotBitmap;
	private Bitmap bitmap[] /* , cameraBitmap */;
	private Bitmap captureBg = null;
	private Bitmap captureInfoBitmap = null;
	private ImageView captureBgImageView;
	private Handler mHandler = new Handler();
	private int focused = 0;
	private int babyCatch = -1;
	private int store_dis_h;
	private int store_dis_l;

	private int uncaptureinfoTime = 0; // 未抓到寶寶警告的秒數
	private Timer timer, uncaptureTimer;

	private SharedPreferences settings;
	// ======音效系統
	private SoundSystem soundSystem;
	private AudioManager audioManager;
	// float ACCELEROMETER = 0;

	private float orientation;
	private int storeHeight;
	private int storeHeightPlus;
	private int storeDistance;

	float oldVal0 = 0;
	float oldVal2 = 0;

	public int angleToScreenX(float angle) {
		focalLength = (float) ((width / 2) / Math.tan((double) CAMERAANGLE / 180 * Math.PI));
		return (int) (focalLength * Math.tan((double) angle / 180 * Math.PI)) + width / 2;
	}

	private float[] oldV = new float[3];

	private float checkAndCalc(float oldV, float newV, float barrier) {
		float delta = oldV - newV;
		if (delta < -barrier || barrier < delta) {
			return (oldV + newV) / 2;
		}
		return oldV;
	}

	private int getDistance(int x1, int y1, int i) {
		x1 = x1 + sampViewList.get(i).getTextureWidth() / 2;
		if (height > 854) {
			y1 = (int) (y1 + (height * 0.7f));
		} else {
			y1 = y1 + height / 2;
		}

		// y1 = y1 + 2 * sampViewList.get(i).getTextureHeight() ;
		// longitude.setText("x1 = " + x1 + ", y1=" + y1 + ", i =" + i);
		return (int) Math.sqrt(Math.pow(x1 - width / 2, 2) + Math.pow(y1 - height / 2, 2));
	}

	private int getDistance_v2(int view_x, int view_y, int aim_x, int aim_y) {
//		 if (view_x < 0 || view_x > Helper.getScreenWidth(this))
//		 return 10000;
//		 if (view_y < 0 || view_y > Helper.getScreenHeight(this))
//		 return 10000;
		//開平方較耗效能
		return (int) /*(Math.sqrt*/(Math.pow(view_x - aim_x, 2) + Math.pow(view_y - aim_y, 2))/*)*/;
	}

	public static Bitmap getBitmapFromView(View view, int width, int height) {
		int widthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
		int heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
		view.measure(widthSpec, heightSpec);
		view.layout(0, 0, width, height);
		Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		view.draw(canvas);
		return bitmap;
	}

	private Handler toastHandler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			Toast.makeText(ARExampleActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
			super.dispatchMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ar_main_layout);
		height = Helper.getScreenHeight(this);
		width = Helper.getScreenWidth(this);

		storeHeight = Helper.getScreenHeight(ARExampleActivity.this) / 2 * -1;
		storeHeightPlus = (int) (Helper.getScreenHeight(ARExampleActivity.this) / 7);
		storeDistance = (int) (storeHeightPlus * 2.1f);
//		storeDistance = (int) (Helper.getScreenHeight(ARExampleActivity.this) / 6);
		mLayout = (FrameLayout) findViewById(R.id.preview_layout);
		latitude = (TextView) findViewById(R.id.latitude);
		longitude = (TextView) findViewById(R.id.longitude);
		high = (TextView) findViewById(R.id.high);
		focus_frame = (ViewFlipper) findViewById(R.id.focus_frame);
		store_switch = (ViewFlipper) findViewById(R.id.store_switch);
		// 抓寶寶按鈕
		toolbtn_Capture = (ImageView) findViewById(R.id.btn_capture);
		toolbtn_CaptureInfo = (ImageView) findViewById(R.id.btn_capture_info);
		toolbtn_Cancel = (ImageView) findViewById(R.id.btn_toolcancel);
		img_CaptureInfo = (ImageView) findViewById(R.id.capture_info);
		img_UncaptureInfo = (ImageView) findViewById(R.id.uncapture_info);
		cancle_CaptureInfo = (ImageView) findViewById(R.id.capture_info_cancel);

		// 音效系統
		soundSystem = SoundSystem.GetInstance(ARExampleActivity.this);
		audioManager = (AudioManager) getSystemService(this.AUDIO_SERVICE);
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		// 相機preview
		mCameraPreview = new CameraPreview(this.getApplicationContext());

		/* 取得感測器服務 */
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

		// mScreenShot = new ImageView(this);
		// mScreenShot.setBackgroundColor(Color.BLACK);
		// RelativeLayout.LayoutParams param = new
		// RelativeLayout.LayoutParams(Helper.getScreenWidth(this),
		// Helper.getScreenHeight(this));
		// mScreenShot.setLayoutParams(param);
		mLayout.addView(mCameraPreview);

		img_UncaptureInfo.setVisibility(View.GONE);
		// mScreenShot.setVisibility(View.GONE);

		Olympic olympicState = (Olympic) getApplicationContext();
		getCameraBabyData = olympicState.getCamerababyData();
		BABY_COUNT = getCameraBabyData.size();
		Log.d("ken", "getCameraBabyData " + getCameraBabyData.size());
		storeInfoData = olympicState.getStoreInfoData();
		Log.d("ken", "storeInfoData " + storeInfoData.size());

		if (storeInfoData.size() > 0) {
			store_dis_h = storeInfoData.get(0).getDistance();
			store_dis_l = storeInfoData.get(0).getDistance();
		}
		for (int i = 0; i < storeInfoData.size(); i++) {
			if (storeInfoData.get(i).getDistance() > store_dis_h) {
				store_dis_h = storeInfoData.get(i).getDistance();
			}
			if (storeInfoData.get(i).getDistance() < store_dis_l) {
				store_dis_l = storeInfoData.get(i).getDistance();
			}
		}
		xList = new int[BABY_COUNT];
		yList = new int[BABY_COUNT];
		isFocus = new boolean[BABY_COUNT];
		// 判對是否第一次開啟
		settings = ARExampleActivity.this.getSharedPreferences("AR", Activity.MODE_PRIVATE);
		boolean isfirst = settings.getBoolean("ARfirst", false);
		if (isfirst == false) {
			img_CaptureInfo.setImageBitmap(null);
			img_CaptureInfo.setVisibility(View.GONE);
			if (captureInfoBitmap != null && !captureInfoBitmap.isRecycled()) {
				captureInfoBitmap.recycle();
				captureInfoBitmap = null;
			}
			cancle_CaptureInfo.setVisibility(View.GONE);
		} else {
			captureInfoBitmap = Helper.readBitMap(ARExampleActivity.this, R.drawable.explain01);
			img_CaptureInfo.setImageBitmap(captureInfoBitmap);
			img_CaptureInfo.setVisibility(View.VISIBLE);
			focus_frame.setVisibility(View.GONE);
			cancle_CaptureInfo.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					focus_frame.setVisibility(View.VISIBLE);
					img_CaptureInfo.setImageBitmap(null);
					img_CaptureInfo.setVisibility(View.GONE);
					if (captureInfoBitmap != null && !captureInfoBitmap.isRecycled()) {
						captureInfoBitmap.recycle();
						captureInfoBitmap = null;
					}
					cancle_CaptureInfo.setVisibility(View.GONE);
				}
			});
		}

		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				focused = 0;
				for (int i = 0; i < BABY_COUNT; i++) {
					if (isFocus[i]) {
						focused++;
						babyCatch = i;
					}
				}
				mHandler.post(new Runnable() {
					public void run() {
						if (focused > 0)
							focus_frame.setDisplayedChild(1);
						else
							focus_frame.setDisplayedChild(0);
					}
				});
			}

		}, 0, 30);

		mOrientationSensors = mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
		mAccelerometerSensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);

		mLocationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
		mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		mLocationManager.getProviders(true);
		mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
			}

			@Override
			public void onProviderEnabled(String provider) {
			}

			@Override
			public void onProviderDisabled(String provider) {
			}

			@Override
			public void onLocationChanged(Location location) {
				user_loc = location;
			}
		});

		if ((!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !mLocationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER))) {

			AlertDialog.Builder dialog = showCustomDialog(false, "「中華加油照集令」要使用\n　　　您當前的位置　　　", 0);
			dialog.setPositiveButton("好", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
					// ARExampleActivity.this.finish();
				}
			});
			dialog.setNegativeButton("不允許", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// Toast.makeText(ARExampleActivity.this,
					// "無法取得目前位置，無法使用本工具!!",
					// Toast.LENGTH_SHORT).show();
					// ARExampleActivity.this.finish();
				}
			});
			dialog.show();
		} else {
			user_loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if (user_loc == null) {
				// if
				// (mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
				// == null) {
				//
				// AlertDialog.Builder dialog = showCustomDialog(false,
				// "「中華加油照集令」要使用\n　　　您當前的位置　　　", 0);
				// dialog.setPositiveButton("好", new
				// DialogInterface.OnClickListener() {
				// public void onClick(DialogInterface dialog, int which) {
				// startActivity(new
				// Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
				// // ARExampleActivity.this.finish();
				// }
				// });
				// dialog.setNegativeButton("不允許", new
				// DialogInterface.OnClickListener() {
				// public void onClick(DialogInterface dialog, int which) {
				// // Toast.makeText(ARExampleActivity.this,
				// // "無法取得目前位置，無法使用本工具!!",
				// // Toast.LENGTH_SHORT).show();
				// // ARExampleActivity.this.finish();
				// }
				// });
				// dialog.show();
				//
				// } else {
				user_loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				// }
			}
		}
		// int aa = -45 + (Helper.getRandom(0, 5));
		int aa = (int) ((width * -0.09375) + (Helper.getRandom(0, 5)));
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.ALPHA_8;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		try {
			BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(opt, true);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (NoSuchFieldException e1) {
			e1.printStackTrace();
		}

		/* 加入商家 */
		Bitmap storeBitmap;
		// Bitmap icon1288 = Helper.readBitMap(ARExampleActivity.this,
		// R.drawable.icon_store_01s);
		// Bitmap iconBigbuy = Helper.readBitMap(ARExampleActivity.this,
		// R.drawable.icon_store_02s);
		for (int i = 0; i < storeInfoData.size(); i++) {
			StoreType storeType;
			if (storeInfoData.get(i).getType() == 1) {
				storeType = StoreView.StoreType.TYPE_1288;
				storeBitmap = Helper.readBitMap(ARExampleActivity.this, R.drawable.icon_store_01s);
			} else {
				storeType = StoreView.StoreType.TYPE_GROUP_BUYING;
				storeBitmap = Helper.readBitMap(ARExampleActivity.this, R.drawable.icon_store_02s);
			}

			StoreView storeView = new StoreView(ARExampleActivity.this, storeInfoData.get(i).getName(), storeInfoData.get(i).getDistance(),
					storeBitmap, storeType);
			storeViewList.add(storeView);
			mLayout.addView(storeView);
			storeBitmap = null;
			// storeView.setOnClickListener(new OnClickListener() {
			// @Override
			// public void onClick(View v) {
			// Intent it = new Intent();
			// it.setClass(ARExampleActivity.this, StoreInfoPageActivity.class);
			// startActivity(it);
			// }
			// });
		}
		/* 商家開關 */
		store_switch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (storeSwitch == true) {
					store_switch.setDisplayedChild(0);
					for (int i = 0; i < storeViewList.size(); i++) {
						storeViewList.get(i).setVisibility(View.VISIBLE);
					}
				} else {
					store_switch.setDisplayedChild(1);
					for (int i = 0; i < storeViewList.size(); i++) {
						storeViewList.get(i).setVisibility(View.GONE);
					}
				}
				storeSwitch = !storeSwitch;
			}
		});
		// TODO StoreView Test
		// Bitmap icon = BitmapFactory.decodeResource(getResources(),
		// R.drawable.ic_launcher);
		// storeView = new StoreView(ARExampleActivity.this, "test", 455, icon,
		// StoreView.StoreType.TYPE_1288);
		// mLayout.addView(storeView);
		// ===========================

		/* 加入寶寶 */
		for (int i = 0; i < BABY_COUNT; i++) {
			bitmap = new Bitmap[10];
			poiList.add(new OriginalParameter(aa + (i * width / 32), 0, 38 - (Helper.getRandom(0, 3))));

//			String temp = getCameraBabyData.get(i).getShowImg().substring(0, 1);
			String temp2 = String.valueOf(Helper.getRandom(2, 15));
			if (temp2.length() == 1) {
				temp2 = "0"+temp2;
			}
			String temp = "camera_2"+temp2+"_";
			for (int j = 0; j < 10; j++) {
				try {
					Bitmap tempbitmap = BitmapFactory.decodeFile("/sdcard/.olympic/" + temp + String.valueOf(j + 1) + ".PNG", opt);
					if (tempbitmap == null) {
						bitmap[j] = Helper.readBitMap(getApplicationContext(),
								Helper.getResId(getApplicationContext(), "drawable", temp + String.valueOf(j + 1)));
					} else {
						bitmap[j] = tempbitmap;
					}
					tempbitmap = null;
				} catch (Exception e) {
					bitmap[j] = Helper.readBitMap(getApplicationContext(),
							Helper.getResId(getApplicationContext(), "drawable", "camera_101_" + String.valueOf(j + 1)));
					Log.e("ken", "bitmapCATCH");
				}
			}

			SampleView view = new SampleView(ARExampleActivity.this, bitmap);
			sampViewList.add(view);
			y_Correction = Math.abs((view.getTextureHeight() >> 1) - (height >> 1));
			// y_Correction = height >> 1;
			x_Correction = Math.abs((view.getTextureWidth() >> 1) - (width >> 1));
			// mCameraPreview.addView(view);
			mLayout.addView(view);
			bitmap = null;

		}

		// mLayout.addView(mScreenShot);
		toolbtn_Capture.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (focused > 0) {
					// 抓到的音效
					soundSystem.playSound(SoundSystem.SOUND_capture);
					// TODO 判斷是否為異業寶寶
					if (getCameraBabyData.get(babyCatch).getBabyType() == 2) { // 判對是否為異業寶寶

						// ===================================================
						Olympic olympicState = (Olympic) getApplicationContext();
						olympicState.setBabyCatchId(getCameraBabyData.get(babyCatch).getBabyId());
						if (PersonalBean.getInstance().getChtsn() != 0) {
							/*  異業合作寶寶累加 */
							IndustryBabyEvent industrybabyEvent = new IndustryBabyEvent(ARExampleActivity.this, String.valueOf(olympicState.getBabyCatchId()) ,getCameraBabyData.get(babyCatch).getGiftProduct());
							industrybabyEvent.addCallback(new IEventCallback() {
								@Override
								public void result(Event event, Object result) {
									if (((IndustryBabyBean) result).getResult() == 0) {
										// TODO 要改
										GetStoreInfoBean getStoreInfoBean = new GetStoreInfoBean();
										getStoreInfoBean.setUrl(getCameraBabyData.get(babyCatch).getUrl());
										getStoreInfoBean.setName(getCameraBabyData.get(babyCatch).getTypeName());
										((Olympic) getApplicationContext()).setStoreInfoBean(getStoreInfoBean);
										Bundle bundle = new Bundle();
										bundle.putInt("type", 3);// 3為異業
										Intent it = new Intent();
										it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										it.putExtras(bundle);
										it.setClass(ARExampleActivity.this, StoreInfoPageActivity.class);
										startActivity(it);
									} else {
										Message msg = toastHandler.obtainMessage(1, "加油寶寶儲存失敗 請重新照集");
										toastHandler.sendMessage(msg);
									}
								}

								@Override
								public void progress(Event event, int progress, String tmpPath) {

								}
							});
							KenEventManager.getInstance().execute(industrybabyEvent);
						}

						// ===================================================

//						GetStoreInfoBean getStoreInfoBean = new GetStoreInfoBean();
//						getStoreInfoBean.setUrl(getCameraBabyData.get(babyCatch).getUrl());
//						getStoreInfoBean.setName(getCameraBabyData.get(babyCatch).getTypeName());
//						((Olympic) getApplicationContext()).setStoreInfoBean(getStoreInfoBean);
//						Bundle bundle = new Bundle();
//						bundle.putInt("type", 3);// 3為異業
//						Intent it = new Intent();
//						it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						it.putExtras(bundle);
//						it.setClass(ARExampleActivity.this, StoreInfoPageActivity.class);
//						startActivity(it);

					} else {// 一般寶寶
						captureBgImageView = new ImageView(ARExampleActivity.this);
						captureBgImageView.setLayoutParams(new LayoutParams(Helper.getScreenWidth(ARExampleActivity.this), Helper
								.getScreenHeight(ARExampleActivity.this)));
						captureBgImageView.setScaleType(ScaleType.FIT_XY);

						/* 設定照集結果背景 */
						int babyId = getCameraBabyData.get(babyCatch).getBabyId();

						/* bitmap options */
						BitmapFactory.Options opt = new BitmapFactory.Options();
						opt.inPreferredConfig = Bitmap.Config.ALPHA_8;
						opt.inPurgeable = true;
						opt.inInputShareable = true;
						try {
							BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(opt, true);
						} catch (IllegalArgumentException e1) {
							e1.printStackTrace();
						} catch (SecurityException e1) {
							e1.printStackTrace();
						} catch (IllegalAccessException e1) {
							e1.printStackTrace();
						} catch (NoSuchFieldException e1) {
							e1.printStackTrace();
						}
						try {
							captureBg = BitmapFactory.decodeFile("/sdcard/.olympic/camera_" + babyId + "_bg.PNG", opt);
							Log.e("ken", "/sdcard/.olympic/camera_" + babyId + "_bg.png");
							if (captureBg == null) {
								captureBg = Helper.readBitMap(ARExampleActivity.this,
										Helper.getResId(ARExampleActivity.this, "drawable", "camera_" + babyId + "_bg"));
							}
							if (captureBg == null) {
								captureBg = Helper.readBitMap(ARExampleActivity.this, R.drawable.camera_99_bg);
								captureBgImageView.setImageBitmap(captureBg);
							} else {
								captureBgImageView.setImageBitmap(captureBg);
							}
						} catch (Exception e) {
							captureBg = Helper.readBitMap(ARExampleActivity.this, R.drawable.camera_99_bg);
							captureBgImageView.setImageBitmap(captureBg);
						}
						captureBg = null;

						ARExampleActivity.this.setContentView(captureBgImageView);
						// mLayout.addView(imageView);
						// mScreenShot.setVisibility(View.VISIBLE);
						Log.d("ken", "babyCatch " + getCameraBabyData.get(babyCatch).getBabyId());
						/* 儲存抓到寶寶ID */
						Olympic olympicState = (Olympic) getApplicationContext();
						olympicState.setBabyCatchId(getCameraBabyData.get(babyCatch).getBabyId());

						dialog = showCustomDialog(true, "您已經成功拍攝到加油寶寶囉！\n　　即刻進行灌溉選手樹　　", babyCatch);
						dialog.setCancelable(false);
						dialog.setPositiveButton("確認", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialoginterface, int i) {
								// mScreenShot.setVisibility(View.GONE);
								// poiList.clear();
								// for (int q = 0; q < BABY_COUNT; q++)
								// poiList.add(new OriginalParameter((int)
								// ((Math.random() * -360) + 180), 50, (int)
								// (Math.random() * 40) - 20));
								captureBgImageView.setImageBitmap(null);
								if (captureBg != null && !captureBg.isRecycled()) {
									captureBg.recycle();
									captureBg = null;
								}
								setResult(TreeActivity.GETBABY_RESULT);
								ARExampleActivity.this.finish();
								/* 清除 */
								mSensorManager.unregisterListener(orientationListener);
								mSensorManager.unregisterListener(accelerometerListener);
								timer.cancel();
								timer = null;
								mLayout.removeAllViews();
								if (sampViewList != null) {
									for (int j = 0; j < sampViewList.size(); j++) {
										sampViewList.get(j).removeBitmap();
									}
								}
								System.gc();

							}
						});
						dialog.show();
					}

				} else {
					// dialog = showCustomDialog(false, "喔喔，沒抓到，要再接再厲呦", 0);
					// dialog.setPositiveButton("確認", new
					// DialogInterface.OnClickListener() {
					// public void onClick(DialogInterface dialoginterface, int
					// i) {
					// }
					// });
					// 未抓到的音效
					soundSystem.playSound(SoundSystem.SOUND_un_capture);

					uncaptureInfoVisible = true;
					img_UncaptureInfo.setVisibility(View.VISIBLE);

					if (uncaptureTimer == null) {
						uncaptureTimer = new Timer();
						uncaptureTimer.schedule(new TimerTask() {
							@Override
							public void run() {
								if (uncaptureInfoVisible == true) {
									if (uncaptureinfoTime < 3) {
										uncaptureinfoTime++;
									} else if (uncaptureinfoTime >= 3) {
										uncaptureinfohandler.sendEmptyMessage(0);
									}
								} else {
									uncaptureinfohandler.sendEmptyMessage(0);
								}

							}
						}, 0, 1000);
					}

				}

			}
		});

		toolbtn_CaptureInfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 資訊圖顯示
				// Cliff add
				((Olympic) ARExampleActivity.this.getApplication()).mPageIndex = Olympic.PageIndex.AR_INFO;
				//
				captureInfoBitmap = Helper.readBitMap(ARExampleActivity.this, R.drawable.explain01);
				img_CaptureInfo.setImageBitmap(captureInfoBitmap);

				img_CaptureInfo.setVisibility(View.VISIBLE);
				cancle_CaptureInfo.setVisibility(View.VISIBLE);
				focus_frame.setVisibility(View.GONE);
				cancle_CaptureInfo.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						focus_frame.setVisibility(View.VISIBLE);
						img_CaptureInfo.setImageBitmap(null);
						img_CaptureInfo.setVisibility(View.GONE);
						if (captureInfoBitmap != null && !captureInfoBitmap.isRecycled()) {
							captureInfoBitmap.recycle();
							captureInfoBitmap = null;
						}
						cancle_CaptureInfo.setVisibility(View.GONE);
						((Olympic) ARExampleActivity.this.getApplication()).mPageIndex = Olympic.PageIndex.AR;
					}
				});
			}
		});

		toolbtn_Cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (uncaptureInfoVisible) {
					img_UncaptureInfo.setVisibility(View.GONE);
					uncaptureInfoVisible = false;
				} else {
					// 關閉
					ARExampleActivity.this.finish();
					mSensorManager.unregisterListener(orientationListener);
					mSensorManager.unregisterListener(accelerometerListener);
					if (timer != null) {
						timer.cancel();
						timer = null;
					}
					mLayout.removeAllViews();
					if (sampViewList != null) {
						for (int i = 0; i < sampViewList.size(); i++) {
							sampViewList.get(i).removeBitmap();
						}
					}
					System.gc();
				}
			}
		});

		// }
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 保持螢幕開啟

		settings.edit().putBoolean("ARfirst", false).commit();// 記錄開啟非第一次

		// TODO 包版用
		// store_switch.setVisibility(View.GONE);
		// store_switch.setDisplayedChild(0);
		// for (int i = 0; i < storeViewList.size(); i++) {
		// storeViewList.get(i).setVisibility(View.GONE);
		// }
	}

	private Handler uncaptureinfohandler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			uncaptureinfoTime = 0;
			img_UncaptureInfo.setVisibility(View.GONE);
			uncaptureInfoVisible = false;
			if (uncaptureTimer != null) {
				uncaptureTimer.cancel();
				uncaptureTimer = null;
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		mCamera = Camera.open();
		mCameraPreview.setCamera(mCamera);
		/** Sensor.TYPE_ACCELEROMETER 加速度 */
		mSensorManager.registerListener(accelerometerListener, mAccelerometerSensors.get(0), SensorManager.SENSOR_DELAY_GAME);
		/** Sensor.TYPE_ORIENTATION方向感應器 */
		mSensorManager.registerListener(orientationListener, mOrientationSensors.get(0), SensorManager.SENSOR_DELAY_GAME);

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mCamera != null) {
			mCameraPreview.setCamera(null);
			mCamera.release();
			mCamera = null;
		}
		mSensorManager.unregisterListener(orientationListener);
		mSensorManager.unregisterListener(accelerometerListener);

	}

	@Override
	public void onBackPressed() {

		this.finish();
		mSensorManager.unregisterListener(orientationListener);
		mSensorManager.unregisterListener(accelerometerListener);
		timer.cancel();
		timer = null;
		mLayout.removeAllViews();
		if (sampViewList != null) {
			for (int i = 0; i < sampViewList.size(); i++) {
				sampViewList.get(i).removeBitmap();
			}
		}
		System.gc();
		super.onBackPressed();
	}

	private SensorEventListener orientationListener = new SensorEventListener() {

		@Override
		public void onSensorChanged(SensorEvent event) {

			int screenX = Helper.getScreenWidth(ARExampleActivity.this) / 50;// TODO
																				// X位移係數可改
			/* 計算商店位置 */

			if (user_loc != null) {

				for (int j = 0; j < storeViewList.size(); j++) {
					float rAngle = rotation_angle;
					if (isPad) {
						if (rotation_angle <= -180) {
							rAngle = rotation_angle + 360;
						}
					} else {
						if (rotation_angle <= -180) {
							rAngle = rotation_angle + 360;
						}
					}

					int x = (Helper.getScreenWidth(ARExampleActivity.this) / 2) - (Math.abs(storeViewList.get(j).getTextureWidth() >> 1));
					// double angle = Math.abs(gps2d(user_loc.getLatitude(),
					// user_loc.getLongitude(),
					// storeInfoData.get(j).getLat(),storeInfoData.get(j).getLng()))
					// + 180;
					double angle = gps2dAngle(user_loc.getLatitude(), user_loc.getLongitude(), storeInfoData.get(j).getLat(), storeInfoData
							.get(j).getLng());
					int x2 = (int) (x + (angle + padAngle - event.values[0] + rAngle) * screenX);

					float yPlus = 0;
					if (j == 0) {
						yPlus = (int) (storeHeight + oldV[2] * 200 /*- ((int) rotation_angle * j)*/);
						storeViewList.get(j).rotateZ(rotation_angle, x2, (int) yPlus, Z_AXIS);
					} else {
						for (int i = j - 1; i >= 0; i--) {
							int viewX = (int) (storeViewList.get(i).matrixValues[2]);
							int viewY = (int) (storeViewList.get(i).matrixValues[5]);
							int center_view_x = (int) (storeViewList.get(j).matrixValues[2]);
							int center_view_y = (int) (storeViewList.get(j).matrixValues[5]);
							if (getDistance_v2(center_view_x, center_view_y, viewX, viewY) <= storeDistance*storeDistance) {
//							if (Math.abs(center_view_x - viewX) <= (width/3.f) || Math.abs(center_view_y - viewY) <= (width/10)) {
								yPlus = (storeViewList.get(i)).getRotateZ_Y() + storeHeightPlus;
								storeViewList.get(j).rotateZ(rotation_angle, (x2), (int) yPlus, Z_AXIS);
								break;
							} else {
								if (i == 0) {
									yPlus = (int) (storeHeight + oldV[2] * 200 /*- ((int) rotation_angle * j)*/);
									storeViewList.get(j).rotateZ(rotation_angle, x2, (int) yPlus, Z_AXIS);
									break;
								}
							}
						}

					}
//					yPlus = (int) (storeHeight + oldV[2] * 200 + ((int) (storeHeightPlus) * j));
//					storeViewList.get(j).rotateZ(rotation_angle, x2, (int) yPlus, Z_AXIS);
					
				}

			}

			// TODO StoreView Test
			// int x = (Helper.getScreenWidth(ARExampleActivity.this) / 2) -
			// (Math.abs(storeView.getTextureWidth() >> 1));
			// double angle = Math.abs(gps2d( user_loc.getLatitude(),
			// user_loc.getLongitude(),25.0482, 121.54023)) + 180;
			// latitude.setText(" 指北values[0] = " +(int) event.values[0]+ " 角度="
			// + angle );
			// int x2 = (int) (x + ( angle - event.values[0]) * screenX);
			// // int x2 = (int) (x + ((gps2dAngle(user_loc.getLatitude(),
			// user_loc.getLongitude(), 25.0482, 121.54023)- (int)
			// event.values[0]) - (rotation_angle)) * screenX);
			// storeView.rotateZ((rotation_angle), x2, -200, Z_AXIS);
			// =======================

			/* 計算寶寶位置 */
			for (int i = 0; i < BABY_COUNT; i++) {

				// float orientation2;
				orientation = (int) event.values[0] - (rotation_angle);
				// orientation2 = event.values[2] + Math.abs(rotation_angle +
				// 90);
				if (orientation > 180) {
					orientation -= 360;
				}
				xList[i] = (int) (((orientation) * -screenX)) - (poiList.get(i).getPosX() * 50);

				sampViewList.get(i).rotateZ((rotation_angle), xList[i] - x_Correction, yList[i] + y_Correction, Z_AXIS);

				// int center_view_x = (int)
				// (sampViewList.get(i).matrixValues[2] + 225);
				// int center_view_y = (int)
				// (sampViewList.get(i).matrixValues[5] + 225);

				int center_view_x = (int) (sampViewList.get(i).matrixValues[0] * 225.0f + sampViewList.get(i).matrixValues[1] * 225.0f + (sampViewList
						.get(i).matrixValues[2]));
				int center_view_y = (int) (sampViewList.get(i).matrixValues[3] * 225.0f + sampViewList.get(i).matrixValues[4] * 225.0f + (sampViewList
						.get(i).matrixValues[5]));

				int center_screen_x = (Helper.getScreenWidth(ARExampleActivity.this) - Helper.dip2px(ARExampleActivity.this, 60 + 25)) / 2;
				int center_screen_y = Helper.getScreenHeight(ARExampleActivity.this) / 2;

				/** 準心 */
				// if (getDistance(xList[i] - x_Correction, yList[i] +
				// y_Correction, i) < DISTANCE) {
				int distance = 0;
				if ((distance = getDistance_v2(center_view_x, center_view_y, center_screen_x, center_screen_y)) < /*225*/ 50625) {
					isFocus[i] = true;
					// Log.e("ken", "center_view_x = " + center_view_x);
				} else {
					isFocus[i] = false;
				}

			}

			oldVal0 = event.values[0];
			oldVal2 = event.values[2];
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};

	private float accCount = 0;
	private float event_Values2_1 = 0;
	private float event_Values2_2 = 0;
	private float event_Values2_old = 0;
	private SensorEventListener accelerometerListener = new SensorEventListener() {

		@Override
		public void onSensorChanged(SensorEvent event) {
			// event_Values2_2 = 0;
			if (accCount <= 5) {
				if (Math.abs(event.values[2] - event_Values2_old) < 0.15f) {
					// event_Values2_1 = event_Values2_1 +
					// (event_Values2_1/accCount);
				} else {
					event_Values2_1 = event_Values2_1 + event.values[2];
					accCount++;
				}
			} else if (accCount > 5) {
				event_Values2_2 = event_Values2_1 / 5;
				event_Values2_1 = 0;
				accCount = 0;
			}

			event_Values2_old = event.values[2];
			oldV[0] = checkAndCalc(oldV[0], event.values[0], 0.188f);
			oldV[1] = checkAndCalc(oldV[1], event.values[1], 0.15f);
			oldV[2] = checkAndCalc(oldV[2], event.values[2], 0.5f);

			event.values[0] = oldV[0];
			event.values[1] = oldV[1];
			event.values[2] = oldV[2];

			// high.setText("acceler 0  " + event.values[0] + "   " +
			// event.values[1] + "   " + event.values[2]);

			for (int i = 0; i < BABY_COUNT; i++) {
				float _g = (float) Math.sqrt(Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2));
				if (Math.abs(event.values[1] - speed) >= 0.2) {
					speed = event.values[1];
					if (event.values[0] >= 0 && event.values[1] >= 0) {
						rotation_angle = (float) ((Math.acos(event.values[1] / _g) / Math.PI) * -180);
					} else if (event.values[0] >= 0 && event.values[1] < 0) {
						rotation_angle = (float) ((Math.acos(event.values[1] / _g) / Math.PI) * -180);
					} else if (event.values[0] < 0 && event.values[1] >= 0) {
						rotation_angle = (float) ((Math.acos(event.values[1] / _g) / Math.PI) * 180);
					} else if (event.values[0] < 0 && event.values[1] < 0) {
						rotation_angle = (float) ((Math.asin(event.values[0] / _g) / Math.PI) * 180) - 180;
					}
					int idx = android.os.Build.MODEL.indexOf("GT-N7000");
					if (width == 800 && height == 1280 && idx == -1) {
						// int sdk_int = Build.VERSION.SDK_INT;
						// TODO forpad
						// if ( sdk_int >=11 && sdk_int <= 13 ) {
						rotation_angle = rotation_angle - 90;
						padAngle = 90;
						isPad = true;
						// }
					}
					int sdk_int = Build.VERSION.SDK_INT;
					if (sdk_int >= 11 && sdk_int <= 13) {
						rotation_angle = rotation_angle - 90;
						// padAngle = 90;
						isPad = true;
					}

					// sampViewList.get(i).rotateZ((rotation_angle + 90),
					// xList[i] - x_Correction, yList[i] + y_Correction,
					// Z_AXIS);
					if (getDistance(xList[i] - x_Correction, yList[i] + y_Correction, i) < DISTANCE) {
						isFocus[i] = true;
					} else {
						isFocus[i] = false;
					}
				}
				int tempAngle = poiList.get(i).getAngle();
				// yList[i] = (int) (((Math.sin(tempAngle) * Distance_to_user) /
				// Math.sin(90 - tempAngle)) + event_Values2_2 * 200);
				yList[i] = (int) (((Math.sin(tempAngle) * Distance_to_user) / Math.sin(90 - tempAngle)) + event.values[2] * 200);
			}
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};

	public AlertDialog.Builder showCustomDialog(boolean baby_show, String text, int baby) {
		AlertDialog.Builder builder;

		LayoutInflater inflater = getLayoutInflater();
		ARExampleActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.ar_custom_dialog, null);
		TextView textView = (TextView) layout.findViewById(R.id.dialog_text);
		textView.setText(text);
		builder = new AlertDialog.Builder(ARExampleActivity.this);
		builder.setView(layout);
		// alertDialog = builder.create();
		// alertDialog.show();
		return builder;
	}

	private static Bitmap takeScreenShot(Activity activity) {
		// View是你需要截圖的View
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap b1 = view.getDrawingCache();

		// 得到狀態列高度
		Rect frame = new Rect();
		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;

		// 得到螢幕長和高　
		int width = Helper.getScreenWidth(activity);
		int height = Helper.getScreenHeight(activity);
		// 去掉標題列
		Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
		view.destroyDrawingCache();
		return b;
	}

	public Bitmap getLocalBitmap(Context con, int resourceId) {
		InputStream inputStream = con.getResources().openRawResource(resourceId);
		return BitmapFactory.decodeStream(inputStream, null, getBitmapOptions(1));
	}

	public BitmapFactory.Options getBitmapOptions(int scale) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPurgeable = true;
		options.inInputShareable = true;
		options.inSampleSize = scale;
		return options;
	}

	// 计算方位角pab。
	private double gps2d(double lat_a, double lng_a, double lat_b, double lng_b) {
		double d = 0;
		lat_a = lat_a * Math.PI / 180;
		lng_a = lng_a * Math.PI / 180;
		lat_b = lat_b * Math.PI / 180;
		lng_b = lng_b * Math.PI / 180;

		d = Math.sin(lat_a) * Math.sin(lat_b) + Math.cos(lat_a) * Math.cos(lat_b) * Math.cos(lng_b - lng_a);
		d = Math.sqrt(1 - d * d);
		d = Math.cos(lat_b) * Math.sin(lng_b - lng_a) / d;
		d = Math.asin(d) * 180 / Math.PI;

		// d = Math.round(d*10000);
		return d;
	}

	public double angToRad(double angle_d) // /度数转弧度
	{
		double Pi = 3.1415926535898;
		double rad1;
		rad1 = angle_d * Pi / 180;
		return rad1;
	}

	private Handler babyMoveHandle = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			/* 計算寶寶位置 */
			for (int i = 0; i < BABY_COUNT; i++) {
				sampViewList.get(i).rotateZ((rotation_angle), xList[i] - x_Correction, yList[i] + y_Correction, Z_AXIS);
			}
			super.dispatchMessage(msg);
		}
	};

	private double gps2dAngle(double lat_a, double lng_a, double lat_b, double lng_b) {
		double lng1 = lng_a;
		double lat1 = lat_a;
		double lng2 = lng_b;
		double lat2 = lat_b;
		double averageLat = (lat1 + lat2) / 2;
		double azimuth;
		if (lat1 - lat2 == 0) {
			azimuth = 90;
		} else {
			azimuth = Math.atan((lng1 - lng2) * Math.cos(angToRad(averageLat)) / (lat1 - lat2)) * 180 / Math.PI;
		}
		if (lat1 > lat2) {
			azimuth = azimuth + 180;
		}
		if (azimuth < 0) {
			azimuth = 360 + azimuth;
		}
		// azimuth = Math.Round(azimuth, 0);
		// textBox5.Text = azimuth.ToString();

		return azimuth;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			for (int i = storeViewList.size() -1; i >= 0 ; i--) {
				int center_view_x = (int) (storeViewList.get(i).matrixValues[2]);
				int center_view_y = (int) (storeViewList.get(i).matrixValues[5]);
				if (event.getX() >= (center_view_x - 40) && event.getX() <= (int) (center_view_x + width / 3 + 40) && event.getY() >= (center_view_y - 40) && event.getY() <= center_view_y + (0.111f * width) + 40) {
					((Olympic) getApplicationContext()).setStoreInfoBean(storeInfoData.get(i));
					Bundle bundle = new Bundle();
					bundle.putInt("type", storeInfoData.get(i).getType());
					// Intent it = new Intent();
					// it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					// it.putExtras(bundle);
					// it.setClass(ARExampleActivity.this,
					// StoreInfoPageActivity.class);
					// startActivity(it);

					Intent it = new Intent(this, StoreInfoPageActivity.class);
					it.putExtras(bundle);
					PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, it, Intent.FLAG_ACTIVITY_NEW_TASK);
					AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
					am.set(AlarmManager.ELAPSED_REALTIME, 100, pendingIntent);
					break;
				}
			}
		}

		return super.onTouchEvent(event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (((Olympic) ARExampleActivity.this.getApplication()).mPageIndex == Olympic.PageIndex.AR_INFO) {
				focus_frame.setVisibility(View.VISIBLE);
				img_CaptureInfo.setImageBitmap(null);
				img_CaptureInfo.setVisibility(View.GONE);
				if (captureInfoBitmap != null && !captureInfoBitmap.isRecycled()) {
					captureInfoBitmap.recycle();
					captureInfoBitmap = null;
				}
				cancle_CaptureInfo.setVisibility(View.GONE);
				((Olympic) ARExampleActivity.this.getApplication()).mPageIndex = Olympic.PageIndex.AR;

				return true;
			}
		}
		/* 調整音量 */
		if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
			audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

}